import preferences from '@ohos.data.preferences';

class PreferencesUtils {
  prefMap: Map<string, preferences.Preferences> = new Map()

  async loadPref(context) {
    try {
      this.prefMap.set('default_preference', await preferences.getPreferences(context, 'default_preference'))
      console.log('testTag', `加载preferences[${'default_preference'}] 成功`)
    } catch (e) {
      console.log('testTag', `加载preferences[${'default_preference'}] 失败`, JSON.stringify(e))
    }
  }

  checkPref(name: string): boolean {
    if (!this.prefMap.has(name)) {
      console.log('testTag', `preferences[${name}] 尚未初始化`)
      return false
    }
    return true
  }

  async putInPref(key: string, value: preferences.ValueType) {
    if (!this.checkPref('default_preference')) return;
    try {
      let pref: preferences.Preferences = this.prefMap.get('default_preference')
      await pref.put(key, value)
      await pref.flush()
      console.log('testTag', `保存preferences[${'default_preference'}：{${key} = ${value}}] 成功`)
    } catch (e) {
      console.log('testTag', `保存preferences[${'default_preference'}：{${key} = ${value}}] 失败`, JSON.stringify(e))
    }
  }

  async getValueInPref(key: string, defaultValue: preferences.ValueType): Promise<preferences.ValueType> {
    if (!this.checkPref('default_preference')) return null
    try {
      let pref: preferences.Preferences = this.prefMap.get('default_preference')
      let value = await pref.get(key, defaultValue)
      console.log('testTag', `读取preferences[${'default_preference'}：{${key} = ${value}}] 成功`)
      return value
    } catch (e) {
      console.log('testTag', `读取preferences[${'default_preference'}：{${key}}] 失败`, JSON.stringify(e))
    }
  }
}

const preferencesUtils = new PreferencesUtils()

export default preferencesUtils as PreferencesUtils